package com.leetcode.partition10;

import java.util.LinkedList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/7/30 9:16
 */
public class LC989数组形式的整数加法 {

    public static List<Integer> addToArrayForm(int[] num, int k) {
        //使用链表的头插法，避免了数组的大量元素移动
        LinkedList<Integer> linkedList = new LinkedList<>();
        int n = 0;              //进位
        int sum;
        for (int i = num.length - 1; i >= 0; i--) {
            int remainder = k % 10;         //取出个位
            k /= 10;
            sum = num[i] + remainder + n;
            linkedList.addFirst(sum % 10);
            n = sum / 10;
        }
        //对k的长度比数组大或者相等的情况进行处理
        k += n;
        while (k != 0) {
            linkedList.addFirst(k % 10);
            k /= 10;
        }
        return linkedList;
    }

    public static void main(String[] args) {
        int[] num = {1, 2};
        int k = 999;
        System.out.println(addToArrayForm(num, k));
    }
}
